<script setup lang="ts">
import {
  // PropType,
  reactive,
  //watch,
  ref,
  unref
} from 'vue'
import { ElRadioGroup, ElRadio, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { Form } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { UploadMultiple } from '@/components/UploadMultiple'
import { useForm } from '@/hooks/web/useForm'
import Sku from './Sku.vue'
import { required } from '@/utils/formRules'
import { shopClassGetTabTreeApi } from '@/api/cs/visit'
import { adminShopShopListeApi } from '@/api/cs/shop'
// import { ucUserListAdminApi } from '@/api/uc/user'
import { adminCsClassListApi } from '@/api/cs/class'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

// const props = defineProps({
//   currentRow: {
//     type: Object as PropType<Nullable<any>>,
//     default: () => null
//   },
//   formSchema: {
//     type: Array as PropType<FormSchema[]>,
//     default: () => []
//   }
// })

const tabTree = ref<any>([])
const tabSelect = ref({})
const classData = ref([])

// 获取该类型的所有标签及标签组
const getVisitClassGetTabTree = async (class_id) => {
  if (class_id) {
    const res: any = await shopClassGetTabTreeApi({ class_id })
      .catch(() => {})
      .finally(() => {})
    // console.log(res)
    if (res) {
      tabTree.value = res.data
      tabSelect.value = {}
    } else {
      tabTree.value = []
      tabSelect.value = {}
    }
  } else {
    // alert('没有类型')
  }
}

const schema: any = [
  { component: 'Input', field: 'goods_name', label: '商品名称' },
  // { component: 'Input', field: 'goods_sn', label: '商品编号' },
  {
    field: 'shop_id',
    label: '所属店铺',
    component: 'DialogRefer',
    componentProps: {
      getListApi: adminShopShopListeApi,
      response: { count: 'count', data: 'data' },
      title: '选择店铺（双击选择）',
      nameField: 'shop_name',
      valueField: 'shop_id',
      crudSchemas: [
        { field: 'shop_name', label: '店铺名称', fixed: 'left', search: { show: true } }
      ]
    }
  },
  // {
  //   field: 'user_id',
  //   label: '创建人',
  //   component: 'DialogRefer',
  //   componentProps: {
  //     getListApi: ucUserListAdminApi,
  //     response: { count: 'count', data: 'data' },
  //     title: '选择创建人（双击选择）',
  //     nameField: 'user_name',
  //     relNameField: 'nickname',
  //     valueField: 'user_id',
  //     crudSchemas: [
  //       { field: 'nickname', label: '姓名', search: { show: true } },
  //       { field: 'username', label: '用户名', search: { show: true } }
  //     ],
  //     modelName: '李天惊'
  //   }
  // },
  {
    component: 'TreeSelect',
    componentProps: {
      onChange: getVisitClassGetTabTree,
      data: classData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'class_id',
      props: { children: 'children', label: 'class_name' }
    },
    field: 'class_id',
    label: '所属分类'
  },
  {
    component: 'InputNumber',
    componentProps: { precision: 2, step: 0.01, mix: 0 },
    field: 'goods_price',
    label: '商品价格'
  },
  { component: 'Upload', field: 'goods_thumbnail', label: '缩略图URL' },
  {
    field: 'is_up_shelf',
    label: '是否上架',
    component: 'Select',
    componentProps: {
      options: dict.is
    }
  },
  {
    component: 'Input',
    componentProps: { type: 'textarea' },
    colProps: { span: 24 },
    field: 'goods_describe',
    label: '商品描述'
  }
]

const rules = reactive({
  goods_name: [required],
  class_id: [required],
  shop_id: [required]
})

const { register, methods, elFormRef } = useForm({
  schema: schema
})
const { setValues } = methods

// watch(
//   () => props.currentRow,
//   (currentRow) => {
//     if (!currentRow) return
//     const { setValues } = methods
//     setValues(currentRow)
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
const data = ref<any>({})
const skuRef = ref<ComponentRef<typeof Sku>>()
const goodsCarouselRef = ref<ComponentRef<typeof UploadMultiple>>()
const goodsDetailsRef = ref<ComponentRef<typeof UploadMultiple>>()
const seeApi = async () => {
  data.value = { ...{}, sku_list: [] }
  setValues(data.value)
}

const getFormData = async () => {
  let formData = await methods.getFormData()
  const sku = unref(skuRef)
  let skuData = sku?.getData()
  const goodsCarousel = unref(goodsCarouselRef) //轮播
  let goods_carousel = goodsCarousel?.getData()
  const goodsDetails = unref(goodsDetailsRef) //明细
  let goods_details = goodsDetails?.getData()
  let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData, ...skuData, goods_carousel, goods_details, goods_tag }
}

// 通过选中值转化成需要写入数据库的值
const getGoodsTag = async () => {
  let new_goods_tag: any = []
  let item: any = {}
  for (let key in tabSelect.value) {
    if (typeof tabSelect.value[key] == 'string') {
      item = { tag_group_id: key, tag_id: tabSelect.value[key] }
      new_goods_tag.push(item)
    } else if (typeof tabSelect.value[key] == 'object') {
      for (let i = 0; i < tabSelect.value[key].length; i++) {
        item = { tag_group_id: key, tag_id: tabSelect.value[key][i] }
        new_goods_tag.push(item)
      }
    } else {
      alert('getGoodsTag 未知类型:' + typeof tabSelect.value[key])
    }
  }
  return new_goods_tag
}

defineExpose({
  elFormRef,
  getFormData
})

const getAdminCsClassListApi = async () => {
  const res: any = await adminCsClassListApi({})
    .catch(() => {})
    .finally(() => {})
  // console.log(res)
  if (res) {
    classData.value = res.data
  }
}
/****************************** 初始化 start ******************************/

const init = async () => {
  // 先调查看详情接口
  await seeApi()
  // 获取分类信息
  await getAdminCsClassListApi()
}
init()

/****************************** 初始化 end ******************************/
</script>

<template>
  <div>
    <Form :rules="rules" @register="register" :data="data" />
    <div class="p-10px">
      <ContentWrap title="选择标签">
        <div v-for="(item, index) in tabTree" :key="index">
          <div>{{ item.label }}:</div>
          <ElRadioGroup v-if="item.select_type == 1" v-model="tabSelect[item.value]">
            <ElRadio
              v-for="(item2, index2) in item.children"
              :key="index + '_' + index2"
              :label="item2.value"
              size="large"
              border
            >
              {{ item2.label }}
            </ElRadio>
          </ElRadioGroup>
          <ElCheckboxGroup v-else-if="item.select_type == 2" v-model="tabSelect[item.value]">
            <ElCheckbox
              v-for="(item2, index2) in item.children"
              :key="index + '_' + index2"
              :label="item2.value"
              size="large"
              border
            >
              {{ item2.label }}
            </ElCheckbox>
          </ElCheckboxGroup>
        </div>
      </ContentWrap>
      <ContentWrap title="轮播图">
        <UploadMultiple
          ref="goodsCarouselRef"
          v-model="data.goods_carousel"
          :response="{
            url: 'goods_carousel_url',
            type: 'goods_carousel_type',
            file_type: 'fileType'
          }"
        />
      </ContentWrap>

      <ContentWrap title="商品详情">
        <UploadMultiple
          ref="goodsDetailsRef"
          v-model="data.goods_details"
          :response="{
            url: 'goods_details_url',
            type: 'goods_details_type',
            file_type: 'fileType'
          }"
        />
      </ContentWrap>
      <Sku ref="skuRef" :sku-list="data.sku_list" :goods-sku="data.goods_sku" />
    </div>
  </div>
</template>
